﻿using System;
using System.Diagnostics;
using Castle.DynamicProxy;
using OWE.Core.Common.Response;
using OWE.Core.Log;
using OWE.Service.Configuration;

namespace OWE.Aspects
{
    public class Performance : IInterceptor
    {
        #region IInterceptor Members

        public void Intercept(IInvocation invocation)
        {
            if (!ConfigManager.GetConfigValue<bool>("PerformanceEnabled", false))
            {
                invocation.Proceed();
                return;
            }
            var stopwatch = new Stopwatch();
            stopwatch.Start();
            try
            {
                invocation.Proceed();
                stopwatch.Stop();
                var response = invocation.ReturnValue as PrimitiveResponse;
                LogEntity log = (response.Log != null) ? response.Log as LogEntity : new LogEntity();
                if (log != null)
                {
                    log.ExecutionTime = stopwatch.ElapsedMilliseconds.ToString();
                    log.LogSeverity = LogSeverity.Performance;
                    log.LogType = LogType.Service;
                    response.Log = log;
                }
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion
    }
}